<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use app\common\model\UserChannel;

/**
 * 服务基础信息
 *
 * @icon fa fa-circle-o
 */
class ServiceBasic extends Backend
{
    protected $searchFields = 'id,name,code';
    /**
     * ServiceBasic模型对象
     * @var \app\common\model\ServiceBasic
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\ServiceBasic;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();

                try {
                    $params['content']=preg_replace("/<\/?o:p.*?>/si","",$params['content']);
                    $params['content']=preg_replace("/<\/?font.*?>/si","",$params['content']);
                    $params['order_notice']=preg_replace("/<\/?o:p.*?>/si","",$params['order_notice']);
                    $params['order_notice']=preg_replace("/<\/?font.*?>/si","",$params['order_notice']);

                    $params['base_price']=$this->setPrice('base_price',$params);
                    $params['hour_price']=$this->setPrice('hour_price',$params);
                    $params['day_price1']=$this->setPrice('day_price1',$params);
                    $params['day_price2']=$this->setPrice('day_price2',$params);
                    $params['day_price3']=$this->setPrice('day_price3',$params);

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? $name : $this->modelValidate;
                        $pk       = $row->getPk();
                        if (!isset($params[$pk])) {
                            $params[$pk] = $row->$pk;
                        }
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $result = $row->save($params);
                    Db::commit();
                }catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $channel_info=UserChannel::all();

        $this->view->assign('base_price', $this->showPrice($row['base_price'], $channel_info));
        $this->view->assign('hour_price', $this->showPrice($row['hour_price'], $channel_info));
        $this->view->assign('day_price1', $this->showPrice($row['day_price1'], $channel_info));
        $this->view->assign('day_price2', $this->showPrice($row['day_price2'], $channel_info));
        $this->view->assign('day_price3', $this->showPrice($row['day_price3'], $channel_info));
        $this->view->assign('row', $row);

        return $this->view->fetch();
    }

    /**
     * 读取价格信息处理
     */
    public function showPrice($price_arr,$channel){

        $price=[];
        foreach ($channel as $c){
            if(array_key_exists($c['id'],$price_arr)){
                $price[$c['name']]=$price_arr[$c['id']];
            }
            else{
                $price[$c['name']]=0;
            }
        }
        if($price===[]){
            $price=['普通用户'=>0];
        }

        return json_encode($price);
    }

    /**
     * 保存价格信息前处理
     */
    public function setPrice($name,$params){
        $price_copy=isset($params[$name])?($params[$name]?json_decode($params[$name]):[]):[];

        $price=[];
        foreach ($price_copy as $k=>$v){
            $channel=UserChannel::getbyName($k);

            if(!$channel){
                throw new Exception('渠道名称错误，请在填写时不要修改价格项中的渠道名');
            }
            $price[(string)$channel['id']]=$v;
        }
        if($price===[]){
            $price=['0'=>0];
        }

        return json_encode($price);
    }

}
